package java6681.bank;

import java6681.lesson13.BankAccount6681;
import java6681.lesson13.BankSynchronized6681;

import java.util.Scanner;

/**
 * @author Junichiro
 * @description
 * @date 2021-06-05 21:56
 **/

public class test {
    private static BankAccount6681 account;

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        account = new BankAccount6681("6681", 1000);
        System.out.println(account.getBankID() +
                "账上开始余额" + account.getBalance() + "元");

        int n = 4;
        Thread[] t = new Thread[n];
        for (int i = 0; i < n; i++) {
            t[i] = new Thread(test::bank6681, "线程" + i);
        }

        for (int i = 0; i < n; i++) {
            t[i].start();
            try {
                t[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(account.getBankID() +
                "账上最终余额" + account.getBalance() + "元");

        long endTime = System.currentTimeMillis();
        long usedTime = (endTime - startTime);
        System.out.println("用时:" + usedTime);
    }

    private static void bank6681() {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        String name = Thread.currentThread().getName();
        String action = "";
        int money = 0, b = 0;
        if (num > 0) {
            money += num;
            action = "存入";
        } else if (num < 0) {
            money += num;
            action = "取出";
        }
        synchronized (test.class) {
            for (int i = 0; i < 1; i++) {
                b = account.getBalance() + money;
                System.out.println(name + action + Math.abs(money));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.setBalance(b);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
